<template>
  <div :class="{'mobile-create-base-report': showMobilePage}" class="create-base-report">
    <div class="report-form">
      <el-form ref="editResouceForm" :model="dataForm" :rules="formRules" label-position="left" class="el-form-box-left" label-width="85px">
        <div class="form">
          <Title :title="title" class="mb-16"/>
          <div class="one-cell">
            <el-form-item label="报表名称" prop="name" class="name">
              <el-input
                v-model.trim="dataForm.name"
                :disabled="isEdit && !isQuote"
                maxlength="20"
                placeholder="请填写报表名称"
                name="name"
                type="text"/>
            </el-form-item>
            <el-select
              v-if="isEdit && detailData && detailData.type === 1 && detailData.sheet.length > 0"
              v-model="dataForm.sheetId"
              name="sheetId"
              class="sheet-select"
              popper-class="global-select-down"
              @change="changeSheet">
              <el-option
                v-for="item in detailData.sheet"
                :key="item.sheetId"
                :label="item.sheetName"
                :value="item.sheetId" />
            </el-select>
          </div>
          <el-form-item label="报表分类" prop="categoryId" class="client-type">
            <el-select :disabled="isDisabled" v-model="dataForm.categoryId" popper-class="global-select-down" name="categoryId">
              <el-option
                :value="0"
                label="全部" />
              <el-option
                v-for="item in categoryList"
                :key="item.id"
                :label="item.name"
                :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="已添加字段" prop="field" class="client-type is-required">
            <SelectField
              ref="selectField"
              :is-show-formula="isShowFormula"
              :field-list-opt="templateFieldListOpt"
              :is-quote-template-field="true"
              :is-show-save-word="false"
              :is-upload-report="isEdit && detailData && detailData.type === 1"
              @setFieldList="setFieldList" />
          </el-form-item>
          <el-form-item label="排序" prop="sortField">
            <div style="display:flex;">
              <div style="height: 30px;">
                <el-switch
                  v-model="isSort"
                  class="fb-switch"
                />
              </div>
              <div v-if="isSort" class="select-sort">
                <!-- 当前选择的字段 -->
                <el-select
                  v-model="sortField"
                  placeholder="字段"
                  name="sortField"
                  popper-class="global-select-down"
                  @change="sortFieldChange">
                  <el-option
                    :value="''"
                    label="请选择" />
                  <el-option
                    v-for="item in fieldListOpt"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id" />
                </el-select>
                <el-select
                  v-model="sortType"
                  placeholder="排序"
                  popper-class="global-select-down"
                  name="sortType">
                  <el-option
                    v-for="item in sortOpt"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id" />
                </el-select>
              </div>
            </div>
          </el-form-item>
          <el-form-item v-if="isShowTiming" label="自动更新" prop="timing">
            <Timing ref="timingComponent" :field-list-opt="fieldListOpt" />
          </el-form-item>
        </div>
      </el-form>
      <fixed-pagination>
        <div class="center">
          <el-button :loading="btnLoading" type="primary" size="small" class="submit-btn" @click="toSubmit">保存</el-button>
          <el-button type="info" size="small" class="back-btn cancel-btn-style" @click="toBack">取消</el-button>
        </div>
      </fixed-pagination>
    </div>
  </div>
</template>
<script>
import { getReportCategory,
  createBaseReport,
  getDetailData,
  getFieldList,
  editBaseReport } from '@/api/reportManage';

import Title from '@/components/Title';
import SelectField from '@/components/ReportManage/selectField/index';
import Timing from '@/components/ReportManage/timing';
import { mapState } from 'vuex';

export default {
  name: 'CreateBaseReport',
  components: { Title, SelectField, Timing },
  data() {
    return {
      title: '新建基础报表',
      btnLoading: false,
      isEdit: false,
      categoryList: [],
      fieldList: [],
      sortOpt: [{ id: 1, name: '正序' }, { id: 2, name: '倒序' }],
      isSort: false,
      dataForm: {
        name: '',
        categoryId: '',
        field: []
      },
      sortField: '',
      sortType: '',
      sortFieldName: '',
      formRules: {
        name: [{ required: true, trigger: 'blur', message: '请填写报表名称' }],
        categoryId: [{ required: true, trigger: 'change', message: '请选择报表分类' }]
      },
      reportId: '',
      sheetId: '',
      detailData: null,
      isShowFormula: false,
      isMessage: false,
      isShowTiming: true
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    isDisabled() {
      return !this.isQuote && (this.isEdit || (this.categoryId !== '' && this.categoryId !== 'all'));
    },
    templateFieldListOpt() {
      const list = this.fieldList.map(i => {
        const obj = {
          name: i.name,
          id: i.id || i.fieldId
        };
        if (i.sourceData) {
          obj.sourceData = i.sourceData;
        }
        return obj;
      }).filter(i => i.id);
      return list;
    },
    fieldListOpt() {
      const list = this.fieldList.map(i => {
        const obj = {
          name: i.name,
          id: i.id || i.fieldId
        };
        if (i.sourceData) {
          obj.sourceData = i.sourceData;
        }
        return obj;
      }).filter(i => i.name);
      list.forEach(i => {
        if (!i.id || i.sourceData) {
          i.id = i.name;
          i.sortFieldName = i.name;
        }
      });
      return list;
    }
  },
  created() {
    this.reportId = this.$route.params.id || '';
    this.sheetId = this.$route.query.sheetId;
    this.isQuote = Number(this.$route.query.quote);
    const categoryId = this.$route.query.categoryId;
    this.categoryId = categoryId;
    if (categoryId && categoryId !== 'all') {
      this.dataForm.categoryId = categoryId === 'all' ? 0 : Number(categoryId);
    }
    this.getTab();
    if (this.isQuote === 1) {
      this.title = '新建基础报表';
      this.isEdit = true;
      this.getDetailData();
    } else {
      if (this.reportId && this.reportId !== '') {
        this.title = '编辑基础报表';
        this.isEdit = true;
        this.getDetailData();
      } else {
        this.title = '新建基础报表';
        this.isEdit = false;
      }
    }
  },
  methods: {
    setFieldList(list) {
      this.fieldList = list;
      if (this.sortField !== '') {
        const ids = this.fieldListOpt.map(i => i.id || i.fieldId);
        if (!ids.includes(this.sortField)) {
          this.sortField = '';
        }
      }
    },
    async getDetailData() {
      try {
        const params = { id: this.reportId };
        if (this.sheetId !== undefined) params.sheetId = this.sheetId;
        const res = await getDetailData(params);
        if (res.data) {
          // 为上传时
          if (res.data.type === 1) {
            this.isShowFormula = true;
            this.isShowTiming = false;
          }
          this.detailData = res.data;
          this.dataForm.name = res.data.name;
          this.dataForm.categoryId = res.data.categoryId || 0;
          this.dataForm.field = res.data.field;
          if (res.data.sheetId) this.dataForm.sheetId = res.data.sheetId;
          this.sortField = res.data.sortField;
          this.sortType = res.data.sortType;
          if (res.data.sortFieldName && res.data.sortFieldName !== '') {
            this.sortField = res.data.sortFieldName;
            this.sortFieldName = res.data.sortFieldName;
          }
          this.$refs.selectField.setDefaultField(res.data.field);
          this.isMessage = res.data.isRegularUpload;
          if (this.$refs.timingComponent) this.$refs.timingComponent.setDefault(res.data);
          if (this.sortField && this.sortField !== '') {
            this.isSort = true;
          } else {
            this.isSort = false;
          }
        }
        // 引用 清空
        if (this.isQuote === 1) {
          this.dataForm.name = this.dataForm.categoryId = '';
        }
      } catch (error) {
        console.error(error);
      }
    },
    changeSheet(sheetId) {
      this.sheetId = sheetId;
      this.getDetailData();
    },
    async getTab() {
      try {
        const res = await getReportCategory();
        if (res.data) {
          this.categoryList = res.data;
        }
      } catch (error) {
        console.error(error);
      }
    },
    toSubmit() {
      const dataForm = this.dataForm;
      const selectField = this.$refs.selectField.checkList;
      const selectRadioList = this.$refs.selectField.radioList; // 关联字段
      // 字段配置
      if (this.isShowFormula && this.$refs.selectFieldRef) {
        /** 公式字段 */
        const combFieldsParams = this.$refs.selectFieldRef.getCombFieldsData();
        dataForm.isSave = combFieldsParams.isSave || false;
        dataForm.combFields = combFieldsParams.combFields || []; // 配置
        /** 公式字段 end */
      }
      dataForm.field = selectField.map(i => {
        const obj = {
          fieldId: i.id || i.fieldId,
          fieldName: i.name,
          isFx: i.isFx,
          sourceId: i.sourceId === '' ? 0 : i.sourceId
        };
        if (i.sourceData) obj.sourceData = i.sourceData;
        return obj;
      });
      let mustField = {};
      if (selectRadioList && selectRadioList.id) {
        mustField = {
          fieldId: selectRadioList.id,
          fieldName: selectRadioList.name,
          isFx: selectRadioList.isFx,
          sourceId: selectRadioList.sourceId === '' ? 0 : selectRadioList.sourceId
        };
        if (selectRadioList.sourceData)mustField.sourceData = selectRadioList.sourceData;
        dataForm.field.unshift(mustField);
      }
      if (this.isSort) {
        dataForm.sortField = this.sortField;
        dataForm.sortType = this.sortType;
        if (this.sortFieldName !== '') {
          dataForm.sortField = '';
          dataForm.sortFieldName = this.sortFieldName;
        } else {
          dataForm.sortField = this.sortField;
        }
      } else {
        dataForm.sortField = null;
        dataForm.sortType = null;
        dataForm.showNums = null;
      }
      dataForm.field = this.removeRepeat(dataForm.field);

      this.$refs['editResouceForm'].validate((valid) => {
        if (valid) {
          // 上传报表不验证 type === 1
          if (this.detailData) {
            if (this.detailData.type !== 1 && (!mustField.fieldId || dataForm.fieldId === '')) {
              this.$message({ type: 'warning', message: '请选择关联字段' });
              return;
            }
          } else {
            if (!mustField.fieldId || dataForm.fieldId === '') {
              this.$message({ type: 'warning', message: '请选择关联字段' });
              return;
            }
          }
          if (dataForm.field.length === 0) {
            this.$message({ type: 'warning', message: '请选择字段' });
            return;
          }
          // 判断是否每个字段都选择了 sourceId
          const isSourceIdError = dataForm.field.some(i => {
            if (i.isFx === 1) {
              return i.sourceId === 0;
            } else {
              return false;
            }
          });
          if (isSourceIdError) {
            this.$message({ type: 'warning', message: '请为已选择的字段选择来源' });
            return;
          }
          // 获取并验证定时更新
          const timingComponent = this.$refs.timingComponent;
          if (timingComponent) {
            const timingParams = timingComponent.getParams(true);
            if (!timingParams) {
              return;
            }
            Object.assign(dataForm, timingParams);
          }
          if (!this.isEdit || this.isQuote === 1) {
            this.createReport(dataForm);
          } else {
            if (this.isMessage && this.isShowTiming) {
              this.$confirm('自动更新已开始导入数据，若修改字段或频率则以往数据无法更新，请确认修改！', '', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                center: true,
                type: 'warning',
                customClass: 'del-message del-message-cancel',
                iconClass: 'del-icon'
              }).then(() => {
                this.editReport(dataForm);
              });
            } else {
              this.editReport(dataForm);
            }
          }
        } else {
          return false;
        }
      });
    },
    createReport(data) {
      this.btnLoading = true;
      createBaseReport(data).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '新建成功'
          });
          this.toBack();
        } else {
          this.$message({
            type: 'error',
            message: res.message
          });
        }
      }).catch((err) => {
        this.btnLoading = false;
        console.log(err);
        // if (err.message !== '网络错误！请检查网络状态...') {
        //   this.$message.error(err.message);
        // }
      });
    },
    editReport(data) {
      data.reportId = this.reportId;
      this.btnLoading = true;
      editBaseReport(data).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '编辑成功'
          });
          this.toBack();
        } else {
          this.$message({
            type: 'error',
            message: res.message
          });
        }
      }).catch((err) => {
        this.btnLoading = false;
        console.log(err);
        // if (err.message !== '网络错误！请检查网络状态...') {
        //   this.$message.error(err.message);
        // }
      });
    },
    removeRepeat(data) {
      const hash = {};
      const newArr = data.reduce((item, next) => {
        if (!hash[next.fieldName]) {
          hash[next.fieldName] = item.push(next);
        }
        return item;
      }, []);
      return newArr;
    },
    toBack() {
      this.$router.push({ name: 'total', query: { categoryId: this.categoryId }});
    },
    async getField(detailField) {
      try {
        const res = await getFieldList({ use: 2 });
        if (res.data) {
          const mustFieldId = [];
          res.data.forEach(i => {
            if (i.name === '关联字段') {
              i.fieldInfo.forEach(j => {
                mustFieldId.push(j.id);
              });
            }
          });
          this.$refs.selectField.setDefaultField(detailField, mustFieldId);
        }
      } catch (error) {
        console.error(error);
      }
    },
    sortFieldChange(id) {
      if (typeof id === 'string') {
        this.sortFieldName = id;
      } else {
        this.sortFieldName = '';
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.create-base-report {
  .report-form {
    margin: 16px 16px 50px 16px;
    background-color: #fff;
    min-height: calc(100vh - 80px);
    padding: 24px;
  }
  .one-cell {
    display: flex;
    .name {
      margin-right: 20px;
    }
  }
}
</style>
<style lang="scss">
.create-base-report {
  .sheet-select {
    .el-input__inner {
      width: 240px;
      height: 30px;
    }
    .el-input__suffix {
      display: flex;
      align-items: center;
    }
  }
  .el-form {
    .el-form-item {
      .el-input__icon {
        line-height: 24px;
      }
      .el-input__inner {
        height: 30px;
        width: 240px;
      }
    }
    .contact-list {
      margin-bottom: 16px;
      &:last-child {
        margin-bottom: 0;
      }
    }
    .add-btn {
      button {
        width: 501px;
        background-color: #f4f4f4;
        border: 1px dashed #e0e0e0;
        color: #777;
        .add-img {
          margin-right: 8px;
        }
      }
    }
  }
  .flex {
    .el-form-item__content {
      display: flex;
      align-items: center;
    }
  }
  .select-sort {
    display: inline-block;
    display: flex;
    .el-input {
      width: 120px !important;
      margin-left: 19px;
    }
    .el-input__inner {
      width: 120px !important;
    }
  }
}
.mobile-create-base-report {
  .report-form {
    margin: 12px 12px 150px 12px !important;
    padding: 12px !important;
    border-radius: 6px;
  }
  .form {
    overflow-x: auto;
    .flex-wrap {
      width: 100%;
      margin: 0;
    }
    .delete-btn, .button-text {
      white-space: nowrap;
    }
  }
  .mobile-data-container {
    max-width: 100%;
    overflow-x: auto;
  }
  ::v-deep {
    .el-form-item {
      width: 100%;
    }
  }
}
</style>
